package org.leviatan.dataharbour.gui.swingmodels;

import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;

import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

import org.leviatan.dataharbour.core.model.DataSource;
import org.leviatan.dataharbour.gui.RuntimeContext;

public class TreeMdlDataSource extends DefaultTreeModel {
	
	private static final long serialVersionUID = -28228330009441949L;

	private DefaultMutableTreeNode theRoot;
	
	private Hashtable<String, TreeNodeMdlDataSource> treeNodeModels;
	
	
	public TreeMdlDataSource() {
		super(new DefaultMutableTreeNode("Data sources"));
		this.theRoot = (DefaultMutableTreeNode) this.getRoot();
		//RuntimeContext.defTree = this;
		
		this.treeNodeModels = new Hashtable<String, TreeNodeMdlDataSource>();
		this.buildTree();
	}

	public void buildTree() {
		
		Map dataSources = RuntimeContext.dataHarbourService.getAllDataSources();
		
		//DataHarbourServiceProxy proxy = RuntimeContext.dataHarbourService;
		
		TreeNodeMdlDataSource nodeMdlDataSource;
		
		// iterate tables
		for (Iterator i = dataSources.values().iterator(); i.hasNext(); ) {
			DataSource dataSource = (DataSource) i.next();
			
			nodeMdlDataSource = new TreeNodeMdlDataSource(dataSource);
			this.theRoot.add(nodeMdlDataSource);
			this.treeNodeModels.put(nodeMdlDataSource.getId(), nodeMdlDataSource);
		}
	}
	
	public TreeNodeMdlDataSource getNodeModel(String id) {
		return this.treeNodeModels.get(id);
	}
	
	
	public void reload() {
		this.theRoot.removeAllChildren();
		this.treeNodeModels.clear();
		this.buildTree();
		super.reload();
	}

	public DefaultMutableTreeNode getTheRoot() {
		return theRoot;
	}

	public void setTheRoot(DefaultMutableTreeNode theRoot) {
		this.theRoot = theRoot;
	}
	

}
